package com.shawn.admin.Statistics;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shawn.admin.mapper.AnalysisMapper;
import com.shawn.admin.mapper.LogMapper;
import com.shawn.commons.utils.RC;
import com.shawn.model.entity.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Component
public class CycleStatistics {


    @Autowired
    private AnalysisMapper analysisMapper;

    @Autowired
    private LogMapper logMapper;
    /**
     * 上传统计数据
     * 每20秒将日志数据统计计算结果上传给数据分析表
     * 秒 分 时 日 周 月 年
     * 1、查询tb_log表中的数 （每日注册用户数，每日登陆用户，活跃的用户数据，次日留存的用户）
     * 2、构造AnalysisByDay对象
     * 3、完成统计数据的更新或者保存
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void uploadStatisticalData() {
        try {
            //1 定义今日日期
            SimpleDateFormat format = new SimpleDateFormat(RC.GENERAL_DATE_FORMAT);
            String today = format.format(new Date());
            //2 定义昨日日期
            String yesterday = DateUtil.yesterday().toString(format);
            //3 统计今日注册数
            Integer registerNum = logMapper.registerNumToday(today);
            //4 统计今日登录数
            Integer loginNum = logMapper.loginNumToday(today);
            //5 统计今日活跃数
            Integer activeNum = loginNum+registerNum;
            //6 统计昨日留存数
            Integer retentionNum = logMapper.queryNumRetention(yesterday, today);

            //查询数据库今日是否已有数据
            LambdaQueryWrapper<Analysis> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Analysis::getRecordDate,today);
            Analysis analysis = analysisMapper.selectOne(wrapper);
            Analysis ana = new Analysis();
            ana.setNumActive(activeNum);
            ana.setNumLogin(loginNum);
            ana.setNumRetention1d(retentionNum);
            if (!Objects.isNull(analysis)){
                //更新数据
                ana.setId(analysis.getId());
                analysisMapper.updateById(ana);
            }else {
                //插入数据
                ana.setRecordDate(format.parse(today));
                analysisMapper.insert(ana);
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
